<template>
	<div class="layout-padding-auto layout-padding-view">
		<el-table v-loading="loading" border :data="tableData">
			<el-table-column prop="name" label="分组名" />
			<el-table-column label="操作" width="200" align="center">
				<template #default="scope">
					<el-button link type="primary" @click="edit(scope.row)" v-auth="'mall:materialgroup:edit'"
						v-if="scope.row.id != '-1'"><el-icon>
							<ele-Edit /> </el-icon>修改</el-button>
					<el-button link type="danger" @click="del(scope.row.id)" v-auth="'mall:materialgroup:del'"
						v-if="scope.row.id != '-1'"><el-icon>
							<ele-Delete /> </el-icon>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<pagination v-model:total="page.total" v-model:currentPage="page.currentPage" v-model:pageSize="page.pageSize"
			@changePage="initPage"></pagination>
	</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue';
import { getPage, editObj, delObj } from '/@/api/mall/materialgroup';
import { ElMessage, ElMessageBox } from 'element-plus';
export default defineComponent({
	setup(props, ctx) {
		const data = reactive({
			page: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
			},
			tableData: [],
			loading: false,
		});

		const initPage = async () => {
			data.loading = true;
			let params = {
				current: data.page.currentPage,
				size: data.page.pageSize,
			};
			await getPage(params)
				.then((response) => {
					data.tableData = response.data.data.records;
					//
					data.tableData.unshift(...[{ name: '未分组', id: '-1' }]);
					data.page.total = response.data.data.total;
					data.loading = false;
				})
				.catch(() => {
					data.loading = false;
				});
		};
		/**
		 * 修改素材
		 */
		const edit = (row: any) => {
			ElMessageBox.prompt('请输入分组名', '修改分组名', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				inputValue: row.name,
			}).then(({ value }) => {
				editObj({ id: row.id, name: value }).then((response) => {
					ElMessage.success('修改成功');
					initPage();
					ctx.emit('initGroup', true);
				});
			});
		};
		/**
		 * 删除分组
		 */
		const del = (id: string) => {
			ElMessageBox.confirm('此操作将删除该分组，是否继续?', '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delObj(id)
					.then((response) => {
						ElMessage.success('删除成功');
						initPage();
						ctx.emit('initGroup', true);
					})
					.catch(() => {
						data.loading = false;
					});
			});
		};

		initPage();
		return {
			edit,
			del,
			initPage,
			...toRefs(data),
		};
	},
});
</script>
<style scoped></style>
